/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package RSSReader;

import java.io.IOException;

import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;


/**
 * @author Christian
 */
public class main extends MIDlet implements CommandListener {

    private Command backToMain, backToFeeds, searchFeeds, showMyFeed, setUserConfig, showAddFeedURL, showDelFeedURL, addFeed, delFeed, showMyFeedDetail, openFeedURL, update, config, search, exit, twitterCommand, twitterProfileOkCommand;
    Form configForm;
    guiManager mgr;
    Display displayDevice;
    Display myDisplay = Display.getDisplay(this);
    private List showRssList;
    private List showRssUrlsList;
    private int userID = 1;


    private RecordStore r_store;
    private TextField txtSearch;

//    private String twitterUser = "";
//    private String twitterPass = "";

    private Displayable currentScreen = null;

    public void startApp()
    {

        showRssUrlsList = new List("Verfügbare RSS-Feeds",List.EXCLUSIVE);
        showMyFeed = new Command("Feed anzeigen", Command.OK, 0);
        showAddFeedURL = new Command("Feed hinzufügen", Command.OK, 1);
        showDelFeedURL = new Command("Feed löschen", Command.OK, 2);
        config = new Command("Konfigurieren", Command.OK, 3);
        search = new Command("Suche", Command.OK, 4);
        exit = new Command("Beenden", Command.OK, 5);
        showRssUrlsList.addCommand(showMyFeed);
        showRssUrlsList.addCommand(showAddFeedURL);
        showRssUrlsList.addCommand(showDelFeedURL);
        showRssUrlsList.addCommand(config);
        showRssUrlsList.addCommand(search);
        showRssUrlsList.addCommand(exit);
        showRssUrlsList.setCommandListener(this);
        
        showRssList = new List("Ausgewähltes RSS-Feeds",List.EXCLUSIVE);
        update = new Command("Aktualisieren", Command.OK, 1);        
        backToMain = new Command("Zurück", Command.OK, 4);
        showMyFeedDetail = new Command("News lesen", Command.OK, 0);


        configForm = new Form("Rss-Reader");
        setUserConfig = new Command("Speichern", Command.OK, 5);
        configForm.addCommand(backToMain);
        configForm.addCommand(setUserConfig);
        //configForm.addCommand(exit);
        //configForm.addCommand(update);
        //configForm.addCommand(config);
        //configForm.addCommand(search);
        configForm.setCommandListener(this);

        showRssList.addCommand(exit);
        showRssList.addCommand(update);
        showRssList.addCommand(backToMain);
        showRssList.addCommand(showMyFeedDetail);
        showRssList.setCommandListener(this);





        mgr = new guiManager(configForm,showRssList,showRssUrlsList,this.userID);
        showRSSUrls();

        //Date d = new Date();

        //System.out.println(String.valueOf(d.getTime()));
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) throws MIDletStateChangeException{
    }
    public void showRSSUrls() {
        this.myDisplay.setCurrent(this.showRssUrlsList);
    }
    public void showRSS() {
        this.myDisplay.setCurrent(showRssList);
    }
    public void showConfig(){
        this.myDisplay.setCurrent(configForm);
    }
    public void showSearch(){

    }

    public void commandAction(Command c, Displayable d)
    {
        // BENUTZER KONFIG SPEICHERN
        if(c.equals(this.setUserConfig))
        {
            String error1 = "";
            String error2 = "";
            String user = "christian";
            String password = "muh";
            int recordID = 0;
             try
             {
                 //TODO
                r_store = RecordStore.openRecordStore("mobile_rss_reader_user", true);
       
                //byte bytesUser[] = user.getBytes();
                //r_store.addRecord(bytesUser,0,bytesUser.length);

                
                //byte bytesPassword[] = password.getBytes();
                //r_store.addRecord(bytesPassword,50,bytesPassword.length);

             } catch (Exception error){ error1 = error.toString(); }


            // USER UND PASSWORT AUS RECORDSTORE
        user = "";
        password = "";


        try
        {
            RecordEnumeration renum = r_store.enumerateRecords(null, null, false);
            while (renum.hasNextElement())
            {
                byte bytesUser[] = r_store.getRecord(1);
                user += new String(bytesUser,0,bytesUser.length);
                int index = renum.nextRecordId();

            }

            //byte bytesPassword[] = r_store.getRecord(50);
            //password = new String(bytesPassword,0,bytesPassword.length);
        } catch (Exception ex) { error2 = ex.toString(); }


            Alert configSaved = new Alert(user + error1 + error2 + " --- ");
            this.myDisplay.setCurrent(configSaved);
           // this.showRssUrlsList.deleteAll();
           // mgr.getRSSListFromServer();
           // showRSSUrls();
        }


        // FEED HINZUFÜGEN
        if(c.equals(this.showAddFeedURL))
        {
            Form addRSS = new Form(null);
            addRSS = mgr.addRSSFeedForm();
            addRSS.setCommandListener(this);
            addRSS.addCommand(backToMain);
            this.addFeed = new Command("Feed hinzufügen", Command.OK, 1);
            addRSS.addCommand(this.addFeed);

            this.myDisplay.setCurrent(addRSS);
        }
        if(c.equals(this.addFeed))
        {
            if(mgr.addRSSFeed(userID))
            {
                Alert feedOK = new Alert("Feed hinzugefügt");
                this.myDisplay.setCurrent(feedOK);
                this.showRssUrlsList.deleteAll();
                mgr.getRSSListFromServer();
                showRSSUrls();
            }
            else
            {
                Alert feednotOK = new Alert("Fehler beim hinzufügen");
                this.myDisplay.setCurrent(feednotOK);
            }
        }


        // FEED LÖSCHEN
        if(c.equals(this.showDelFeedURL))
        {
            Form delRSS = new Form(null);
            delRSS = mgr.delRSSFeedForm();
            delRSS.setCommandListener(this);
            delRSS.addCommand(backToMain);
            this.delFeed = new Command("Feed löschen", Command.OK, 1);
            delRSS.addCommand(this.delFeed);

            this.myDisplay.setCurrent(delRSS);
        }
        if(c.equals(this.delFeed))
        {
            if(mgr.delRSSFeed(showRssUrlsList.getSelectedIndex(), userID))
            {
                Alert feedOK = new Alert("Feed gelöscht");
                this.myDisplay.setCurrent(feedOK);
                
                this.showRssUrlsList.deleteAll();
                mgr.getRSSListFromServer();
                showRSSUrls();
            }
            else
            {
                Alert feednotOK = new Alert("Fehler beim löschen");
                this.myDisplay.setCurrent(feednotOK);
            }
        }

        // FEEDS ABRUFEN
        if(c.equals(this.showMyFeed))
        {
            mgr.loadRSSFeed(showRssUrlsList.getSelectedIndex(), userID, "");
            showRSS();
        }

        // FEED DETAIL ANZEIGEN
        if(c.equals(this.showMyFeedDetail))
        {
            Form displayNews = new Form(null);
            displayNews = mgr.readRSSNews(showRssList.getSelectedIndex());
            displayNews.setCommandListener(this);
            openFeedURL = new Command("URL öffnen", Command.OK, 1);
            backToFeeds = new Command("Zurück", Command.OK, 0);

            displayNews.addCommand(openFeedURL);
            displayNews.addCommand(backToFeeds);
            twitterCommand = new Command("twitter", Command.OK, 2);
            displayNews.addCommand(twitterCommand);
            myDisplay.setCurrent(displayNews);
        }

        // FEED URL IM BROWSER ÖFFNEN
        if(c.equals(this.openFeedURL))
        {
            try
            {
                platformRequest(mgr.getRSSUrl());
            }
            catch (ConnectionNotFoundException ex) {  }
        }

        //Twitter User Form OK
        if (c.equals(twitterProfileOkCommand))
        {
            this.myDisplay.setCurrent(currentScreen);
//            this.twitterUser = mgr.getTwitterUserName();
//            this.twitterPass = mgr.getTwitterPassword();
            twitterAMessage();
        }


        //Twitter a News
        if (c.equals(twitterCommand))
        {
            if (twitterAMessage()) {
                return;
            }
//            } catch (BadTokenStateException ex)
//            {
//
//            }
        }
        
        // ZURÜCK
        if(c.equals(this.backToMain))
        {
            showRSSUrls();
        }

        // AKTUALISIEREN
        if(c.equals(this.update) || c.equals(this.backToFeeds))
        {
            showRSS();
        }

        // KOFIGURIEREN
        if (c.equals(this.config))
        {
            mgr.loadConfigScreen();
            showConfig();

        }

        // SUCHEN
        if (c.equals(this.search))
        {
            Form frmSearch = mgr.addSearchForm();
            frmSearch.setCommandListener(this);
            this.txtSearch = new TextField("Suchbegriff", null,50, TextField.ANY);
            frmSearch.append(this.txtSearch);

            this.searchFeeds = new Command("Suche starten", Command.OK, 1);
            frmSearch.addCommand(this.backToMain);
            frmSearch.addCommand( this.searchFeeds);

            myDisplay.setCurrent(frmSearch);
        }
        if(c.equals(this.searchFeeds))
        {
            mgr.loadRSSFeed(showRssUrlsList.getSelectedIndex(), userID, this.txtSearch.getString());
            showRSS();
            
            //Alert alert = new Alert( "" + id);
            //myDisplay.setCurrent(alert);
            
        }

        // BEENDEN
        if (c.equals(this.exit))
        {
            try {
                destroyApp(false);
            } catch (MIDletStateChangeException e) {
                e.printStackTrace();
            }
            notifyDestroyed();

        }
    }

    private boolean twitterAMessage() {
        try {
            Twitter t = new Twitter();
            //if (twitterUser.equals(""))
            if (mgr.getTwitterUserName().equals(""))
            {
                currentScreen = myDisplay.getCurrent();
                Form twitterUserForm = new Form("Twitter Account");
                mgr.addTwitterConfigToForm(twitterUserForm);
                twitterProfileOkCommand = new Command("OK", Command.OK, 0);
                twitterUserForm.addCommand(twitterProfileOkCommand);
                twitterUserForm.setCommandListener(this);
               
                myDisplay.setCurrent(twitterUserForm);

                return true;
            }
            if (t.twitterMsg(mgr.getRSSUrl(), mgr.getTwitterUserName(), mgr.getTwitterPassword()))
           // if (t.twitterMsg(mgr.getRSSUrl(), this.twitterUser, this.twitterPass))
            {
                Alert msg = new Alert("Nachricht getwittert!");
                msg.setTimeout(Alert.FOREVER);
                this.myDisplay.setCurrent(msg);
            } else {
                Alert msg = new Alert(t.getLastResponse());
                msg.setTimeout(Alert.FOREVER);
                this.myDisplay.setCurrent(msg);
            }
//            } catch (OAuthServiceProviderException ex) {
//                ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
//            } catch (BadTokenStateException ex)
//            {
//
//            }
        return false;
    }
}
